package com.demo.javaee.project.json.servlet;

import com.demo.javaee.project.common.JsonResp;
import com.demo.javaee.project.h2Jdbc.H2Jdbc;
import com.demo.javaee.project.json.model.StudentDTO;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

/**
 *
 * @author Lychee
 * @author nisuangewo
 * @date 2019-11-28
 *
 * */

@WebServlet(urlPatterns = "/student")
public class StudentServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Jsonb jsonb = JsonbBuilder.create();
//        req.setCharacterEncoding("UTF-8");

        String postJson = new BufferedReader(new InputStreamReader(req.getInputStream()))
                .lines().collect(Collectors.joining(System.lineSeparator()));
        StudentDTO studentDTO = jsonb.fromJson(postJson, StudentDTO.class);
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        H2Jdbc h2Jdbc = new H2Jdbc();
        boolean result = h2Jdbc.save(studentDTO);
        JsonResp jsonResp = new JsonResp();
        if (result) {
            jsonResp.setCODE("1");
            jsonResp.setMESSAGE("ok 保存成功");
        } else {
            jsonResp.setCODE("0");
            jsonResp.setMESSAGE("fail 保存失败");
        }
        String respJson = jsonb.toJson(jsonResp);
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        resp.getWriter().println(respJson);
    }
}
